#include "s_stm32_rtc.h"
#include "h_stm32_hal_defines.h"
#include <stdio.h>
#include <string.h>
#include "s_utc_2_normaltime.h"

#define RTC_MASK_VALUE			0xc0de

extern RTC_HandleTypeDef hrtc;

static signed char s_stm32_rtc_get_date_time(RTC_DateTypeDef *date, RTC_TimeTypeDef *time)
{
	HAL_StatusTypeDef rslt;
	rslt = HAL_RTC_GetTime(&hrtc, time, RTC_FORMAT_BIN);
	rslt += HAL_RTC_GetDate(&hrtc, date, RTC_FORMAT_BIN);
	if(rslt != HAL_OK) {
		return (-1);
	}
	return 0;
}

static signed char s_stm32_rtc_set_date_time(RTC_DateTypeDef *date, RTC_TimeTypeDef *time)
{
	HAL_StatusTypeDef rslt;
	rslt = HAL_RTC_SetTime(&hrtc, time, RTC_FORMAT_BIN);
	rslt += HAL_RTC_SetDate(&hrtc, date, RTC_FORMAT_BIN);
	if(rslt != HAL_OK) {
		return (-1);
	}
	return 0;
}
     
unsigned int s_stm32_rtc_get_utc(void)
{
	unsigned int utc = 0U;
	s_normaltime_str date_t;

	RTC_TimeTypeDef time;
	RTC_DateTypeDef date;
	if(s_stm32_rtc_get_date_time(&date, &time)) {
		return 0;
	}
	
	// printf("the sec is %d\r\n", time.Seconds);
	// printf("time: 20%02d-%d-%d %d:%d:%d\r\n", date.Year, date.Month, date.Date, time.Hours, time.Minutes, time.Seconds);
	// printf("wek is %d\r\n", date.WeekDay);
	date_t.year = 2000 + date.Year;
	date_t.month = date.Month;
	date_t.day = date.Date;
	date_t.hour = time.Hours;
	date_t.min = time.Minutes;
	date_t.sec = time.Seconds;
	date_t.weeknum = s_utc2normaltime_getweeknum(date_t.year, date_t.month, date_t.day);

	// printf("it is week %d\r\n", date_t.weeknum);

	S_NormalTime2UTC(&date_t, &utc);

	// printf("the utc is %d\r\n", utc);
	return utc;
}

signed char s_stm32_rtc_set_utc(unsigned int utc)
{
	s_normaltime_str date_t;
	RTC_TimeTypeDef time;
	RTC_DateTypeDef date;

	S_UTC2NormalTime(utc, &date_t);

	date.Year = date_t.year - 2000;
	date.Month = date_t.month;
	date.Date = date_t.day;
	date.WeekDay = date_t.weeknum;
	time.Hours = date_t.hour;
	time.Minutes = date_t.min;
	time.Seconds = date_t.sec;

	return s_stm32_rtc_set_date_time(&date, &time);
}

signed char s_stm32_rtc_restore_mask(void)
{
	HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, RTC_MASK_VALUE);
	return 0;
}

signed char s_stm32_rtc_isNotMasked(void)
{
	if(RTC_MASK_VALUE != HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR1)) {
		return (-1);
	}
	return 0;
}

// signed char s_stm32_rtc_init(void)
// {
// 	if(s_stm32_rtc_isNotMasked()) {
		
// 	}
// 	return 0;
// }

void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
{
	printf("alarmed\r\n");
}